<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'FtpHelper.php';
/**
 * 处理xml文件，导入数据
 * @author Administrator
 *
 */
class importdata{
    private $basePath="/data/webroot/minicms/web/public/images/";
	private function db()
    {   
        $params = array ('host' => '192.168.1.16',
                 'port' => '3306',
                 'username' => 'root',
                 'password' => 'soooner.com',
                 'charset' => 'UTF8',
                 'dbname'   => 'minicms');
        $db = Zend_Db::factory('PDO_MYSQL', $params);
        return $db;
    }
    
    function getConfig()//获取配置信息
    {
    	$db = $this->db();
    	$configrows = $db->fetchAll("select configname, configvalue from config");//获取配置信息
        $configs = array();
    	if (!empty($configrows)){
	       foreach ($configrows as $item){
	          $configs[$item['configname']] = $item['configvalue'];}
    	}//配置信息获取完成
    	return $configs;
    }
    
    function getSpecMap()//获取epg名称和对应关系,暂时不用
    {
    	$db = $this->db();
    	$maprows = $db->fetchAll("select max(contentid) contentid, title from content where contenttype =2 and STATUS = 99 group by title");//获取信息
        $maps = array();
    	if (!empty($maprows)){
	       foreach ($maprows as $item){
	          $maps[$item['title']] = $item['contentid'];}
    	}//配置信息获取完成
    	return $maps;
    }
    function createLinkCommand()
	{
		$dir ="/data/link/";
		if ($dh = opendir($dir)) {
	        while (($file = readdir($dh)) !== false) {
	        	if(strpos($file,".xml"))
	        	{
	        		try{
	        			$this->createLink($file);
	        		}
	        		catch (Exception $e){
	        			echo 'Caught exception: ',  $e->getMessage(), "\n";
	        		}	        		
	        	}
	        }
	        closedir($dh);
	    }
	}
	
	function createLink($xmlfile)//从文件导入epg信息
    {
		$dir ="/data/link/";
		if($xmlfile){
			try{
				$ok = false;			
				//读出xml为doc
				$fp = fopen($dir.$xmlfile, 'r');
				$xmldata = fread($fp, filesize($dir.$xmlfile));
				fclose($fp);
				$doc = new DOMDocument();
				$doc->loadXML($xmldata);
				$items = $doc->getElementsByTagName("v");
				//数据库链接
				$db = $this->db();
				$db->beginTransaction();
				foreach($items as $item)
				{
					$vid = $item->getElementsByTagName("vid")->item(0)->nodeValue;
					$title = $item->getElementsByTagName("title")->item(0)->nodeValue;
					$director = $item->getElementsByTagName("director")->item(0)->nodeValue;
					$act = $item->getElementsByTagName("act")->item(0)->nodeValue;
					$type = $item->getElementsByTagName("type")->item(0)->nodeValue;
					$tag1 = $item->getElementsByTagName("catalog")->item(0)->nodeValue;
					$tag2 = $item->getElementsByTagName("area")->item(0)->nodeValue;
					$tag3 = $item->getElementsByTagName("year")->item(0)->nodeValue;
					$imgurl = $item->getElementsByTagName("imgurl")->item(0)->nodeValue;
					$state = $item->getElementsByTagName("state")->item(0)->nodeValue;
					$mark = $item->getElementsByTagName("mark")->item(0)->nodeValue;
					$bitrate = $item->getElementsByTagName("bitrate")->item(0)->nodeValue;
					$resolution = $item->getElementsByTagName("resolution")->item(0)->nodeValue;
					$duration = $item->getElementsByTagName("duration")->item(0)->nodeValue;
					$content = $this->getDetail($vid);
		            $ok = true;//确认xml文件是好的
		            
		            $insertcontentsql = "insert into vod (title, type, director, act, tag1, tag2, tag3, imgurl,state,mark,bitrate,resolution,duration,content)values (:title, :type, :director, :act, :tag1, :tag2, :tag3, :imgurl,:state,:mark,:bitrate,:resolution,:duration,:content)";
	            	$db->query($insertcontentsql,array("title"=>$title,"type"=>$type,"director"=>$director,"act"=>$act,"tag1"=>$tag1,"tag2"=>$tag2,"tag3"=>$tag3,"imgurl"=>$imgurl,"state"=>$state,"mark"=>$mark,"bitrate"=>$bitrate,"resolution"=>$resolution,"duration"=>$duration,"content"=>$content));
	            	$vid = $db->lastInsertId();
	            	$db->query("insert into vodlist (vid, title) values (:vid, :title)",array("vid"=>$vid, "title"=>$title));
	            	$this->downloadImg($imgurl,$vid);
		        }
		        $db->commit();
			}
			catch (Exception $e){
				$db->rollBack();
				echo 'Caught exception: ',  $e->getMessage(), "\n";
			}
    	}
    }
    
    function getDetail($vid){
    	try{
    		echo $vid;
	    	$url="http://epg.ppbox.pplive.com/detail.ashx?&vid=$vid&auth=d410fafad87e7bbf6c6dd62434345818";
	    	$c=file_get_contents($url);
	    	$doc = new DOMDocument();
			$doc->loadXML($c);
			$content = $doc->getElementsByTagName("content")->item(0)->nodeValue;
			return $content;
    	}catch (Exception $e){
    		echo $e;
			return "";
    	}
    }
    function saveImg(){
    	$db = $this->db();
    	$vods = $db->fetchAll("select vid,imgurl from vod");//获取信息
    	foreach ($vods as $vod){
    		echo $vod["vid"];
    		$this->downloadImg($vod["imgurl"],$vod["vid"]);
    	}
    }
	function downloadImg($sourceImg,$imgId)
	{
		$ext=substr($sourceImg,strripos($sourceImg,"."));
		$folder=floor($imgId/500);
		if (!file_exists($this->basePath.$folder)){
		           mkdir($this->basePath.$folder,"0755",true);
		}
		$img = file_get_contents($sourceImg); 
		$savePath = $this->basePath.$folder."/".$imgId.$ext;
		file_put_contents($savePath,$img);
		if($ext!=".com")
			return $this->wwwRoot.$folder."/".$imgId.$ext;
		else
			return 0;
	}
    
    function updateuuidCommand()//更新内容中心节目的uuid
    {
    	$db = $this->db();
    	$rows = $db->fetchAll("select contentid, urllow, urlmedium, urlhigh from c_vod where urlhigh like 'http://nrzx%'");//获取配置信息
        foreach($rows as $row)
        {
        	$uuid = $this->uuid($row["urlmedium"]);
        	$contentid = $row["contentid"];
        	echo $uuid."=======================================";
        	$db->query("update c_vod set uuidlow=:uuid, uuidmedium=:uuid, uuidhigh=:uuid where contentid = :contentid",array("uuid"=>$uuid,"contentid"=>$contentid));
        }
    }
    
    
	private function uuid($FileUrl,$Rate=2000,$SPID='JSCN00000003',$RC4_SYS_KEY='VSDNSOOONERCOM00')
	{
	    $chn = "[chn]".$SPID."|".$FileUrl."|".basename($FileUrl)."|1[/chn][rate]".$Rate."[/rate]";
	    $uuid = bin2hex(pack('a*', $chn)).$RC4_SYS_KEY;
	    return $uuid;
	}
	
	
	function getFtpList()
	{
		$config = $this->getConfig();
		$ftp = new FtpHelper('111.208.57.130',21,'jscn01','jscn');
		$p = iconv( "UTF-8", "GB18030","/");
		$files = $ftp->proc_all_files($config["nrzx_path"],"/");//已经处理的文件列表
		$filename = date("Y-m-d");
		$xmlpath = "/data/vod/".$filename.".xml";
		$this->createXml($files,$xmlpath);
		$this->publish($files,$config);
		foreach($files as $f)//删除下载成功的文件
		{
			if($f[3])//下载成功
				$ftp->move_file($f[0],$f[0].".del",false);
				//$ftp->del_file($f[0]);
		}
		print_r($files);//删除下载成功的文件
		$ftp->close();
	}
	
	/**
	 * 发布到webcms中
	 */
	private function publish($arrs,$config)
	{
		try{
			//读出需要的数据
			$map = $this->getSpecMap();
			print_r($map);
			$catid = 80;	
			$userid = "JSCN00000003";	
			$db = $this->db();
			//从表名称			
			$tablename = $this->db()->fetchOne("select model.tablename from model left join category on model.modelid=category.modelid where category.catid = :catid",array("catid"=>$catid));
			$db->beginTransaction();
			for($i=0;$i<count($arrs);$i++){
				if($arrs[$i][3]==1){
					$img="";
					$relationid = $i;
					$realpath = $arrs[$i][1];//真实路径
					$title = $arrs[$i][2];
					$description = $title = $arrs[$i][2];
					$special = $arrs[$i][4];
					$date = $arrs[$i][5];				
					//$url = str_replace("/nrzx-nfs","http://nrzx.bigtv.com.cn/data9", $arrs[$i][1]);
					$url = str_replace($config["nrzx_path"],$config["nrzx_url"], "$realpath");
			        $uuid = $this->uuid($url);    
			        $insertcontentsql = "insert into content (catid, title, keywords, status, userid, username, inputtime,updatetime, isonline, contenttype,tablename,template,tumbmedium,relationid,realpath,dateorder) values 
			    			('$catid','$title','$title','3','$userid','system','".time()."','".time()."','1','1','$tablename','show_record','$img','$relationid','$realpath','$date')";
			        $db->query($insertcontentsql);
			        $contentid = $db->lastInsertId();
			        $db->query("insert into $tablename (contentid, content, urllow,urlmedium,urlhigh,uuidlow,uuidmedium,uuidhigh,endtime) values (:contentid, :content, :urllow, :urlmedium, :urlhigh, :uuidlow, :uuidmedium, :uuidhigh, :endtime)",array("contentid"=>$contentid, "content"=>$description, "urllow"=>$url,"urlmedium"=>$url,"urlhigh"=>$url,"uuidlow"=>$uuid,"uuidmedium"=>$uuid,"uuidhigh"=>$uuid,"endtime"=>$config["nrzx_end"]));
			        $specialid = $map[$special];
			        if($specialid){
			        	$db->query("insert into special_content (specialid, contentid, listorder, contenttype,dateorder) values (:specialid, :contentid, :listorder, :contenttype, :dateorder)",array("specialid"=>$specialid, "contentid"=>$contentid, "listorder"=>$contentid, "contenttype"=>"2","dateorder"=>$date));
			        }
				}
			}
	        $db->commit();
		}
		catch (Exception $e){
			$db->rollBack();
			syslog(LOG_INFO, ": publish - ".$e);
		}
	}
	
	/**
	 *生成xml文件
	 *
	 */
	private function createXml($arrs,$xmlpath)
	{
		$content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
		$content .= "<items catgoryid=\"195\" special=\"1\" userid=\"JSCN00000005\">\n";
		
		for($i=0;$i<count($arrs);$i++){
			if($arrs[$i][3]==1){//如果处理成功才生成节点
				$special = "";
				$date = "";
				$title = $arrs[$i][2];
				$special = $arrs[$i][4];
				$date = $arrs[$i][5];				
				//$url = str_replace("/nrzx-nfs","http://nrzx.bigtv.com.cn/data9", $arrs[$i][1]);
				$url = str_replace($config["nrzx_path"],$config["nrzx_url"], $realpath);
				$content .= "<item id=\"$i\">\r\n";
				$content .= "\t<special>$special</special>\r\n";
				$content .= "\t<date>$date</date>\r\n";
				$content .= "\t<title>$title</title>\r\n";
				$content .= "\t<description>$title</description>\r\n";
				$content .= "\t<img></img>\r\n";
				$content .= "\t<url>$url</url>\r\n";
				$content .= "\t<start></start>\r\n";
				$content .= "\t<end></end>\r\n";
				$content .= "</item>\r\n";
			}
		}
		$content .= "</items>\r\n";
		//$filename = date("Y-m-d");
		//$file = fopen($path.$filename.".xml","w");
		$file = fopen($xmlpath,"w");
		echo fwrite($file,$content);
		fclose($file);
	}
}

$cmd=$argv[1]; 
if($cmd=="createLink"){//清节目单
	$test = new importdata();
	$test->createLinkCommand();
	syslog(LOG_INFO, ": commands - createLinkCommand.");
}
if($cmd=="updateuuid"){//更新uuid
	$test = new importdata();
	$test->updateuuidCommand();
	syslog(LOG_INFO, ": commands - updateuuidCommand.");
}
if($cmd=="ftpcheck"){
	$test = new importdata();
	$test->getFtpList();
	syslog(LOG_INFO, ": commands - ftpcheck.");
}
if($cmd=="saveimg"){
	$test = new importdata();
	$test->saveImg();
	syslog(LOG_INFO, ": commands - saveImg.");
}